﻿using System;
using System.Collections.Generic;
using System.Text;
//new
using DataRecv.models.sdk.DAHUASDK;
using System.Threading;
using DataRecv.tools;
using DataRecv.models.device;

namespace DataRecv.models.recever
{
    public class Recever_DH
    {
        private fDisConnect m_disConnect;       //设备离线消息
        private fHaveReConnect m_onlineMsg;     //设备重新在线消息



        public Recever_DH()
        {
            try
            {
                DHClient.DHSetShowException(false);//不抛出异常信息

                m_disConnect = new fDisConnect(DisConnectEvent);
                bool flag = DHClient.DHInit(m_disConnect, IntPtr.Zero);

                m_onlineMsg = new fHaveReConnect(OnlineEvent);
                DHClient.DHSetAutoReconnect(m_onlineMsg, IntPtr.Zero);

                if (flag == true)
                {
                    LogTool.log.Info("DHSDK初始化成功");
                }
                else
                {
                    LogTool.log.Info("DHSDK初始化失败");
                }
            }
            catch { }
        }

        private void DisConnectEvent(int lLoginID, StringBuilder pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            try
            {
                string camip = pchDVRIP.ToString();
                if (G.Devices != null)
                {
                    for (int i = 0; i < G.Devices.Count; i++)
                    {
                        if (G.Devices[i].deviceview.deviceparam.ip == camip)
                        {
                            G.Devices[i].state.Ping = false;
                            G.Devices[i].state.PingOccurTime = DateTime.Now;
                            DHClient.DHStopLoadPic(G.Devices[i].state.AlarmHandle);
                            G.Devices[i].state.AlarmHandle = -1;
                            LogTool.log.Info("DH摄像机---" + camip + "---连接中断");
                            break;
                        }
                    }
                }
            }
            catch { }
        }

        private void OnlineEvent(int lLoginID, StringBuilder pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            try
            {
                string camip = pchDVRIP.ToString();
                if (G.Devices != null)
                {
                    for (int i = 0; i < G.Devices.Count; i++)
                    {
                        if (G.Devices[i].deviceview.deviceparam.ip == camip)
                        {
                            G.Devices[i].state.Ping = true;
                            G.Devices[i].state.PingOccurTime = DateTime.Now;
                            LogTool.log.Info("DH摄像机---" + camip + "---恢复连接");
                            break;
                        }
                    }
                }
            }
            catch { }
        }


        public void Close()
        {
            try
            {
                DHClient.DHCleanup();
            }
            catch { }
        }
    }
}
